<template>
  <div class="dataCard" v-loading="spinLoading">
    <!-- 顶部区域 具有 抽样参数 近似计算参数 -->
    <div class="crumbs">
      <header class="crumbs_box">
        <grid-menu></grid-menu>
        <span class="tool_main">
          <el-date-picker
            v-if="time_show"
            @change="time_change"
            v-model="time_screen"
            size="mini"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
          <el-tooltip
            v-if="!time_show"
            class="tool_son"
            effect="light"
            content="时间范围"
            placement="bottom"
          >
            <i @click="showTimeRange" class="el-icon-date"></i>
          </el-tooltip>

         <el-tooltip class="tool_son" effect="light" content="筛选条件" placement="bottom">
           <i @click="screen_show=true" class="el-icon-set-up"></i>
         </el-tooltip>
          <el-tooltip class="tool_son" effect="light" content="刷新" placement="bottom">
            <i class="el-icon-refresh" style="cursor: pointer;" v-if="!refreshLoading" @click="handleRefresh"></i>
            <i class="el-icon-loading" v-if="refreshLoading"></i>
          </el-tooltip>
        </span>
      </header>
    </div>

		<div v-if="card_arr.length > 0">
			<vuedraggable
				v-loading="panelLoading"
				element-loading-background="transparent"
				@update="datadragEnd"
				v-model="card_arr"
				class="group_box"
				:options="{animation:500, ghostClass:'sortable-ghost',chosenClass:'chosenClass',scroll:true,scrollSensitivity:200}"
			>
				<transition-group>

					<template v-for="_i in card_arr">
						<cardShow :key="_i.id" @del_card="del_card_arr" :configInit="_i"></cardShow>
					</template>

				</transition-group>
			</vuedraggable>
		</div>
		<div class="card-no-result" v-else>
			<span class="icon"><i class="el-icon-data-line"></i></span>
			<p class="msg">还未添加指标组件</p>
			<el-button
				type="primary"
				size="medium"
				@click="com_add=true"
				v-if="(overviewGroupType == 0 && $currentRole > 2) || overviewGroupType == 1">
				新建组件
			</el-button>
		</div>

    <!-- 筛选弹框 -->
    <el-dialog
      top="15vh"
      :modal-append-to-body="false"
      class="diglog_box"
      :visible.sync="screen_show"
      width="50%"
      title="概览筛选23"
    >
      <div class="screen-content">
        <div class="screen_config">
          <!-- 事件属性 -->
          <div class="screen_one">
            <div class="top">
              <i
                @click="event_screen_show=!event_screen_show"
                :class="event_screen_show?'el-icon-arrow-down':'el-icon-arrow-right'"
              ></i>
              <i class="el-icon-notebook-1"></i>
              事件属性
            </div>
            <div v-show="event_screen_show" class="screen_cont">
              <conditionScreening
                :key="updateNumTotal"
                deep
                add
                :limit="1"
                ref="computedTreeEvent"
                @change="handleChangeEventFilter"
                :filterEnter="config.eventFilter"
                :fieldArr="config.fieldArrEvent"
              ></conditionScreening>

              <div class="total_screen" @click="$refs.computedTreeEvent.initAdd()">
                <i class="el-icon-plus"></i>
                全局筛选
              </div>
            </div>
          </div>
          <!-- 用户属性 -->
          <div class="screen_one">
            <div class="top">
              <i
                @click="user_screen_show=!user_screen_show"
                :class="user_screen_show?'el-icon-arrow-down':'el-icon-arrow-right'"
              ></i>
              <i class="el-icon-user"></i>
              用户属性
            </div>
            <div v-show="user_screen_show" class="screen_cont">
              <conditionScreening
                :key="updateNumTotal"
                deep
                add
                :limit="1"
                ref="computedTreeUser"
                @change="handleChangeUserFilter"
                :filterEnter="config.userFilter"
                :fieldArr="config.fieldArrUser"
              ></conditionScreening>

              <div class="total_screen" @click="$refs.computedTreeUser.initAdd()">
                <i class="el-icon-plus"></i>
                全局筛选
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="diglog_foot">
        <el-button :size="size" @click="screen_show = false">取 消</el-button>
        <el-button :size="size" type="primary" @click="screen_show = false">确 定</el-button>
      </span>
    </el-dialog>

    <!--	新建组件弹框	-->
    <el-dialog
      top="15vh"
      :modal-append-to-body="false"
      class="dialog_box"
      :visible.sync="com_add"
      width="40%"
      title="新建组件"
    >
      <div class="com-list">
        <div
          class="item"
          v-for="(item, index) in com_list"
          :key="index"
          @click="handleSelectCom(item)"
        >
          <div class="content">
            <div class="icon">
              <i :class="item.icon"></i>
            </div>
            <p>{{item.txt}}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import cardShow from "./cardShow.vue";
import vuedraggable from "vuedraggable";
// import screeningVerificationSmall from "./screeningVerification_small.vue";
import conditionScreening from "@/components/conditionScreening/computedTree.vue";
import gridMenu from "./gridMenu";

export default {
  name: "dataCard",
  components: {
    cardShow,
    vuedraggable,
    conditionScreening,
    gridMenu
  },
  data() {
    return {
      spinLoading: false,
      panelLoading: false, // 面板loading
      timeChangeBool: false, // 判断时间是否改变
      // 概览筛选
      updateNumTotal: 0, // 刷新变量 全局筛选
      config: {
        eventFilter: null,
        userFilter: null,
        fieldArrEvent: [],
        fieldArrUser: []
      },
      event_screen_show: true, // 事件属性筛选下拉开关
      user_screen_show: true, // 用户属性筛选下拉开关
      // 日期：快捷
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      refreshLoading: false,
      screen_show: false, // 全体概览的筛选条件开关
      time_show: false, // 是否进行时间筛选
      time_screen: [], // 时间筛选绑定值
      size: "small",

      com_add: false // 新建组件dialog
    };
  },

  methods: {
    showTimeRange() {
      this.time_show = true;
      let today = this.$moment();
      console.log(today);
      this.time_screen = [today, today];
    },
    // 全局筛选内容改变返回值
    handleChangeEventFilter(value) {
      this.config.eventFilter = value;
    },
    handleChangeUserFilter(value) {
      this.config.userFilter = value;
    },
    // 获取全局筛选下的第一列可选值
    async fieldArrTotalGet() {
      let res = await this.$analysisApi.eventAnalysis.eventAnalysisPropertyList(
        {
          appId: this.appId,
          eventId: ""
        }
      );
      if (res&&res.success) {
        if (
          res.value.eventPropertyList &&
          res.value.eventPropertyList.length > 0
        ) {
          this.config.fieldArrEvent.push({
            id: Math.random()
              .toString(36)
              .substr(2),
            name: "事件属性",
            children: res.value.eventPropertyList
          });
          console.log("fieldArrEvent", this.config.fieldArrEvent);
        }
        if (
          res.value.userPropertyList &&
          res.value.userPropertyList.length > 0
        ) {
          this.config.fieldArrUser.push({
            id: Math.random()
              .toString(36)
              .substr(2),
            name: "用户属性",
            children: res.value.userPropertyList
          });
          console.log("fieldArrUser", this.config.fieldArrUser);
        }
      }
    },
    // 刷新
    handleRefresh() {
      this.refreshLoading = true;
      this.handleQueryOverviewComponentList();
    },
    // 查询概览组件列表
    async handleQueryOverviewComponentList() {
      this.panelLoading = true;
      let data = {
        overviewId: this.overviewItem ? this.overviewItem.id : "",
        currentPage: 1,
        pageSize: 10000
      };
      if (this.time_screen && this.time_screen.length > 0) {
        let fromDate = this.$moment(this.time_screen[0]).format("YYYY-MM-DD");
        let toDate = this.$moment(this.time_screen[1]).format("YYYY-MM-DD");
        data.fromDate = fromDate;
        data.toDate = toDate;
      }

      try {
        let res = await this.$analysisApi.dataCard.overviewComponentList(data);
        if (res) {
          let { list } = res.value;
          list = list.map(item => {
            item.windowSize === Number(item.windowSize);
            if (item.queryJson) {
              let queryJson = JSON.parse(item.queryJson);
              if (item.chartType == 4) {
								if (!queryJson.req) {
									// 兼容漏斗原有报文格式
									queryJson = {
										req: queryJson
									};
								}
								console.log('queryJson ===>>', queryJson);
                if (this.time_screen.length > 0) {
                  queryJson.fromDate = data.fromDate;
                  queryJson.toDate = data.toDate;
									queryJson.req.fromDate = data.fromDate;
									queryJson.req.toDate = data.toDate;
                }
              } else {
                if (this.time_screen.length > 0) {
                  queryJson.searchTime.startDate = data.fromDate;
                  queryJson.searchTime.endDate = data.toDate;
                }
              }
              item.queryJson = JSON.stringify(queryJson);
            }
            return item;
          });
          this.$store.commit("dataCard/card_arr_change", list);
          setTimeout(() => {
						this.panelLoading = false;
						this.refreshLoading = false;
					}, 500);
        }
      } catch (e) {
				this.$message({
					type: "error",
					message: e.message
				});
        this.panelLoading = false;
				this.refreshLoading = false;
      }
    },
    // 拖拽结束
    datadragEnd(evt) {
      let arr = JSON.parse(JSON.stringify(this.card_arr));
      let item = this.card_arr[evt.oldIndex];
      arr.splice(evt.oldIndex, 1);
      arr.splice(evt.newIndex, 0, item);
      this.$store.commit("dataCard/card_arr_change", arr);
      evt.preventDefault();
    },
    // 时间改变
    time_change() {
      this.timeChangeBool = true;
      if (!this.time_screen) {
        this.time_show = false;
      }
      this.handleQueryOverviewComponentList();
    },
    // 删除card
    del_card_arr(obj) {
      let _in = "killer";
      let _arr = [];
      this.card_arr.map((_i, _ins) => {
        _arr.push(_i);
        if (_i.id == obj.id) {
          _in = _ins;
        }
      });
      if (_in !== "killer") {
        _arr.splice(_in, 1);
      }
      this.$store.commit("dataCard/card_arr_change", _arr);
    },
    // 选择组件分析
    handleSelectCom(item) {
      this.$router.push({
        path: item.name
      });
    }
  },
  created() {
    this.fieldArrTotalGet();
  },
  mounted() {},
  computed: {
    appId() {
      return this.$store.state.global.appId;
    },
    ...mapState({
      overviewItem: state => state.global.overviewItem,
      overviewGroupType: state => state.global.overviewGroupType,
      appItem: state => state.global.appItem
    }),
    // 数据看板组大对象
    ...mapState("dataCard", {
      card_arr: state => state.card_arr
    }),
    // dialog: 组件分析list
    com_list() {
      let menuList = this.$store.state.dataAnalysis.data_analysis_menuList;
      let list = [];
      if (menuList) {
        menuList.map(item => {
          if (item.children && item.children.length > 0) {
            item.children.map(child => {
              list.push(child);
            });
          } else {
            list.push(item);
          }
        });
      }
      return list;
    }
  },
  watch: {
    overviewItem: {
      handler(val) {
        console.log(val, "overviewItem-data");
        this.spinLoading = false;
        this.timeChangeBool = false;
        this.$store.commit("dataCard/card_arr_change", []);
        if (val) {
          this.handleQueryOverviewComponentList();
        } else {
          this.panelLoading = true;
          setTimeout(() => {
            this.panelLoading = false;
          }, 200);
        }
      },
      immediate: true
    },
    appItem: {
      handler(val) {
        console.log(val, "appItem11");
        // this.spinLoading = true;
        this.$store.commit("dataCard/card_arr_change", []);
      },
      immediate: true
    }
  }
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

// 全局筛选
.total_screen {
  padding: 10px 0;
  width: 99%;
  margin: 0 auto;
  height: 40px;
  display: flex;
  align-items: center;
  color: #307ef2;

  i {
    font-weight: 800;
    margin: 0 10px 0 0;
  }
}

.group_box {
  background: rgba(238, 238, 238, 1);
  width: 100%;
  padding: 0.2rem 0 2rem;
  clear: both;
	height: 100vh;

  .min {
    width: 23%;
    height: 3rem;
    margin: 0.2rem 1%;
    // width: 340px;
    // margin: 20px 10px;
    // height: 200px;
  }

  .mid {
    width: 48%;
    height: 6.4rem;
    margin: 0.2rem 1%;
    // width: 700px;
    // height: 440px;
    // margin: 20px 10px;
  }

  .big {
    width: 98%;
    height: 6.4rem;
    margin: 0.2rem 1%;
  }

  .card_group {
    float: left;
    display: inline-block;
    border-radius: 6px;
    box-sizing: border-box;
    transition: all 0.4s ease;
    background-color: #fff;
    border: 2px solid transparent;
  }

  .card_group:hover {
    border-color: rgba($color: #01b27a, $alpha: 0.6);
  }

  footer {
    width: 100%;
    margin: 0 auto;
    min-height: 0.4rem;
    float: left;
  }
}

.card-no-result {
  text-align: center;
  margin-top: 25vh;

  .icon {
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    vertical-align: middle;
    display: inline-block;
    background: #fff;
    border-radius: 50%;
    font-size: 30px;
  }

  .msg {
    font-size: 20px;
    font-weight: 500;
  }
}

.crumbs_box {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .tool_main {
    padding: 0 0.5rem 0 10px;
    font-size: 12px;
    font-weight: 500;
    color: #606266;
    // line-height: 44px;
    letter-spacing: 2px !important;

    .select {
      margin: 0 6px;
    }

    .fgf {
      display: inline-block;
      width: 1px;
      height: 16px;
      background: #c0c4cc;
      margin: 0 0.4rem;
    }

    .tool_son {
      font-size: 16px;
      margin: 0 0.1rem;
      font-size: 0.26rem;
    }

    .tool_son:hover {
      color: #01b27a;
      font-weight: 600;
    }

    .el_casc {
      margin: 0 0rem 0 0.2rem;
    }
  }
}

.dataCard::-webkit-scrollbar {
  display: none;
}

.dataCard {
  width: 98%;
  margin: 0 auto;
  box-sizing: border-box;
  height: 98.6%;
  overflow: scroll;
}

// 级联样式
.one_line {
  display: flex;
  width: 100%;
  align-items: center;
  border-radius: 4px;
  height: 40px;

  i {
    font-weight: 800;
    opacity: 0;
  }

  .tools_one {
    margin: 0 0.2rem;
    opacity: 0;
  }

  .tools_one:hover {
    color: #007aff;
    font-weight: 500;
  }

  .err {
    margin: 0 0.1rem;
  }

  .err:hover {
    color: red;
    font-size: 16px;
  }
}

.one_line:hover {
  background: rgba($color: #f2f6fc, $alpha: 0.9);

  i,
  .tools_one {
    opacity: 1;
  }
}

.deep_screen .one_line:hover {
  background: rgba($color: #409eff, $alpha: 0.2);
}

.total_screen_show {
  //   border-top: 1px solid #ebeef5;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  //   margin: 10px 0;
  .left {
    height: 100%;
    width: 0.2rem;
    position: absolute;

    .tree_btn {
      position: absolute;
      left: 60%;
      top: 50%;
      padding: 6px 4px;
      font-size: 10px;
      border-radius: 4px;
      background: #dcdfe6;
      transform: translate(-50%, -50%);
    }

    .tree_btn:hover {
      background: rgba($color: #01b27a, $alpha: 1);
      color: rgba($color: white, $alpha: 0.9);
    }
  }

  .right {
    width: calc(100% - 30px);
    margin-left: 30px;
    box-sizing: border-box;
  }
}

// 弹窗
.diglog_box {
  .screen-content {
    position: relative;
  }

  .screen_config {
    width: 100%;
    min-height: 3rem;
    /*max-height: 6.2rem;*/
    /*overflow-y: scroll;*/
    scrollbar-width: none; /*Firefox*/
    -ms-overflow-style: none; /*IE10+*/
    .screen_one {
      width: 99%;
      margin: 0 auto 0rem;

      .top {
        width: 100%;
        cursor: pointer;
        height: 0.6rem;
        background: rgba($color: #f5f8fc, $alpha: 1);
        display: flex;
        align-items: center;
        padding-left: 0.2rem;

        i {
          font-size: 10px;
          margin: 0 0.2rem 0 0;
          font-weight: 600;
        }

        i:nth-child(1) {
          margin: 0 0.4rem 0 0;
          font-weight: 800;
        }

        i:nth-child(1):hover {
          color: rgba($color: #01b27a, $alpha: 0.6);
        }
      }

      .screen_cont {
        width: 100%;

        .add {
          padding: 0 0 0 0.2rem;
          width: 99%;
          margin: 0 auto;
          cursor: pointer;
          height: 40px;
          display: flex;
          align-items: center;
          color: #307ef2;

          i {
            font-weight: 800;
            margin: 0 10px 0 0;
          }
        }
      }
    }
  }

  .screen_config::-webkit-scrollbar {
    display: none;
  }
}
</style>
<style lang="scss">
.diglog_box {
  .el-dialog__body {
    overflow: visible;

    .paramsArr {
      min-width: 1rem;

      .el-input {
        width: 150px;
      }
    }
  }
}

.com-list {
  .item {
    width: calc(100% / 3);
    display: inline-block;
    text-align: center;
    color: #5f6e82;
    border-radius: 3px;
    padding: 5px 10px;

    .content {
      cursor: pointer;
      padding: 10px 0;
      background: #f5f8fc;
      border: 1px solid #e9f0f7;

      &:hover {
        border-color: #2dca93;
        color: #2dca93;
      }

      .icon {
        display: inline-block;
        width: 50px;
        height: 50px;
        line-height: 50px;
        background: #fff;
        border-radius: 50%;
        font-size: 20px;
      }
    }
  }
}
</style>
